//
//  String+extension.swift
//  iUtil
//
//  Created by wendachuan on 19/3/22.
//  Copyright © 2019年 wendachuan. All rights reserved.
//

import Foundation

public extension String {
    static let emptyString = ""

    /// 将可选型字符串转换为非可选型
    ///
    /// - parameter input: 输入的可选型字符串
    /// - returns: 非可选型字符串
    static func toNoneNIL(_ input: String?) -> String {
        return input != nil ? input! : emptyString
    }

    /// 将Unmanaged字符串转换为String
    ///
    /// - parameter cfValue: 输入的可选型字符串
    /// - returns: 转换后的字符串
    static func convertCfTypeToString(_ cfValue: Unmanaged<NSString>!) -> String? {
        /* Coded by Vandad Nahavandipoor */
        let value = Unmanaged<CFString>.fromOpaque(
            cfValue.toOpaque()).takeUnretainedValue() as CFString
        if CFGetTypeID(value) == CFStringGetTypeID() {
            return value as String
        } else {
            return nil
        }
    }

    /// 从String中截取不超过指定字节数的子串
    ///
    /// - parameter maxBytes: 指定的最大字节数
    /// - returns: 子串
    func subStringWithMaxBytes(_ maxBytes: Int) -> String {
        var buffer = [UInt8].init(repeating: 0, count: maxBytes)
        var length: Int = 0
        
        let range = Range<String.Index>.init(uncheckedBounds: (lower: self.startIndex, upper: self.endIndex))
        var remain = Range<String.Index>.init(uncheckedBounds: (lower: self.startIndex, upper: self.endIndex))
        if self.getBytes(&buffer, maxLength: maxBytes, usedLength: &length, encoding: String.Encoding.utf8, options: NSString.EncodingConversionOptions.allowLossy, range: range, remaining: &remain) {
            if let subStr = String.init(bytes: buffer.prefix(length), encoding: String.Encoding.utf8) {
                return subStr
            }
        }

        return String.emptyString
    }

    /// 从String中截取不超过指定字符数的子串
    ///
    /// - parameter maxChars: 指定的最大字符数
    /// - returns: 子串
    func subStringWithMaxCharacters(_ maxChars: Int) -> String {
        if self.count > maxChars {
            return String(self[..<self.index(self.startIndex, offsetBy: maxChars)])
        } else {
            return String(self)
        }
    }

    /// 从字符串分析宽高比
    /// - parameter aspectString: 形如4:3的待分析字符串
    /// - returns: 分析出的宽高比或nil
    static func parseAspectRatio(fromString aspectString: String) -> (first: Int, second: Int)? {
        var splitArray = aspectString.split(separator: ":")
        if splitArray.count == 2 {
            let first = Int(String(splitArray[0]))
            let second = Int(String(splitArray[1]))
            if first != nil && second != nil {
                return (first!, second!)
            }
        }
        return nil
    }
    
    /// 获得字符串的日期值
    ///
    /// - returns: 如果字符串能转换为日期，则返回日期值；否则返回nil
    func dateValue() -> Date? {
        do {
            var date: Date? = nil
            let semaphore = DispatchSemaphore(value: 0)
            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
            detector.enumerateMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.lengthOfBytes(using: String.Encoding.utf8)), using: { (checkingResult, _, _) in
                date = checkingResult?.date
                semaphore.signal()
            })
            semaphore.wait()
            return date
        } catch _ {
            return nil
        }
    }
}
